import { accessToken, signIn, logout, getInfo } from '@/api/login'
import { oauthCallback } from "@/api/oauth/socialoauth"
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import { notifySignIn } from "@/signalR/user";
const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      features: [],  //功能模块
      ipInfo: { address: '', ip: "" },
      hasLocalEmail: false,
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const captcha = userInfo.captcha
        const connectionId = userInfo.connectionId
        return new Promise((resolve, reject) => {
          accessToken(username, password, captcha, connectionId).then(res => {
            setToken(res)
            this.token = res
          }).then(s => {
            return signIn();
          }).then(s => {
            resolve();
          }).catch(error => {
            reject(error)
          })
        })
      },
      socialLogin(code, provider, redirectUrl) {
        return new Promise((resolve, reject) => {
          let query = { code, provider, redirectUrl }
          oauthCallback(query).then(res => {
            setToken(res)
            this.token = res
          }).then(s => {
            return signIn();
          }).then(() => {
            resolve();
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : user.avatar;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.id
            this.name = user.nickName
            this.hasLocalEmail = user.localEmail
            this.avatar = avatar
            this.features = user.features;
            this.ipInfo = user.ipInfo;
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
